package com.liu.shop.address.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liu.shop.address.entity.AddressEntity;
import com.liu.shop.address.service.AddressService;
import com.liu.shop.common.constant.AuthConstants;
import com.liu.shop.common.exception.BusinessException;
import com.liu.shop.common.utils.PageUtils;
import com.liu.shop.common.utils.R;
import com.liu.shop.common.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;
import java.util.Map;



/**
 * @author lls
 * @email 302140431@qq.com
 * @date 2021-08-24 17:42:13
 */
@RestController
@RequestMapping("/address")
@Slf4j
public class AddressController {
    @Autowired
    private AddressService addressService;


    /**
     * 获取用户的收货地址
     * @param uid
     * @return
     */
    @GetMapping("/getAddressListByUid/{uid}")
    public List<AddressEntity> getAddressListByUid(@PathVariable Integer uid){
        return addressService.list(new QueryWrapper<AddressEntity>().eq("uid",uid));
    }

    /**
     * 添加地址信息
     * 因为用户新添加的地址信息可能设为默认的，
     * 所以要调用MySQL中的存储过程（相当于mysql中的方法）
     * @param
     * @return
     */
    @PostMapping("/addAddress")
    public R addAddress(@RequestBody AddressEntity addressEntity,HttpSession session ){
        // 获取用户登录的信息
        UserVo userVo = (UserVo) session.getAttribute(AuthConstants.LOGIN_USER);
        log.debug("用户登录信息:{}",userVo);
        // 如果用户没有登录就抛出异常
        if (userVo == null) {
            throw new BusinessException("您还没有登录，请先登录", 002);
        }
        addressEntity.setUid(Integer.parseInt(userVo.getId()));
        addressService.insertAddress(addressEntity);
        return R.ok();

    }



    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = addressService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public AddressEntity info(@PathVariable("id") Integer id){
		AddressEntity address = addressService.getById(id);
        return address;
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody AddressEntity address){
		addressService.save(address);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody AddressEntity address){
		addressService.updateById(address);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Integer[] ids){
		addressService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

    @RequestMapping("/deleteById")
    public R deleteById(@RequestParam Integer aid){
        addressService.removeById(aid);
        return R.ok();
    }

}
